%Kernels for faces

function experimentOneFaceJuan(subject)


%initial parameters
%Screen('Preference', 'SkipSyncTests', 1); %this is to work in LABS computer
screenNum=0;
%screen size (in pixels)
scrWidth = 800;% 1024;
scrHeight = 600; %768;
res=[scrWidth scrHeight];
clrdepth=32;
[wPtr, rect]=Screen('OpenWindow', screenNum, 0, [0 0 res(1) res(2)], clrdepth);
filename=strcat('RAW_',subject)
fileID=fopen(filename,'w');

%headers NOT working, ascii vs binary issue...
%fprintf(fileID,'trial starting noises(1 to sequenceSize) male confidence\n'); 
%fwrite(fileID, 'trial starting noises(1 to sequenceSize) male confidence\n'); 

white=WhiteIndex(wPtr);
Screen('FillRect', wPtr, white);

%compute monitor's refresh rate
refresh = Screen('GetFlipInterval', wPtr);
Screen('Flip', wPtr);

%image gallery parameters:
folder = '../incc2009/Stimuli/morph/morph';
%folder = 'C:\Documents and Settings\Administrador\Escritorio\incc\svn\incc2009\Stimuli\morph\morph';
%fileExt = '';
qtyFaces = 50;
imgHeight = 540;
imgWidth = 720;

%experiment variables:
tpp = 0.050; %time per picture
qtyFrames = round(tpp/refresh); %qty of frames per picture based on monitor's refresh rate.
sequenceSize = 40; %quantity of images to be shown for each sequence (size of trial)
qtyTrials = 300;

%keyCodes:

%mac
%leftMore = 9; %f
%leftLess = 7; %d
%rightMore = 13; %j
%rightLess = 14; %k

%linux ?
leftMore = 42; %f
leftLess = 41; %d
rightMore = 45; %j
rightLess = 46; %k

%windows ?
%leftMore = 70; %f
%leftLess = 68; %d
%rightMore = 74; %j
%rightLess = 75; %k


%radius of movement for the selected faces. 
sigma = 4;


%preallocate gallery image holders
gallery = cell(1,qtyFaces);

%load images
DrawFormattedText(wPtr, 'Cargando im�genes... (esto puede demorar unos segundos)', 100, scrHeight/2);
Screen('Flip',wPtr);

try
    for i=1:qtyFaces
        file = strcat(folder, num2str(i-1));
        gallery{i} = Screen('MakeTexture', wPtr, imread(file));
    end
catch er
    rethrow(er)
end

%%%%%%%%%%%% Adaptive muZero testing %%%%%%%%%%%%%
DrawFormattedText(wPtr, 'A continuaci�n se har�n unos rounds de prueba para ajustar par�metros', 100, scrHeight/2);
Screen('Flip',wPtr);

femaleIndex = 49;
maleIndex = 0;
maleTurn = binornd(1,0.5);
muZero = -1;
step = 5;

while(muZero < 0)
    %Check that indexes don't overpass each other
    if (femaleIndex < 25 && maleIndex >= 25)
        muZero = 25;
        break;
    end
    
    if(maleTurn == 1)
        k = maleIndex;
        maleIndex = maleIndex + step;
    else
        k = femaleIndex;
        femaleIndex = femaleIndex - step;
    end
    
    Screen('DrawTexture', wPtr, gallery{k+1}, [0 0 imgWidth imgHeight], [0 0 scrWidth scrHeight]); %resize to fill screen
    Screen('Flip', wPtr);
    waitSecs(1.5);
    DrawFormattedText(wPtr, 'Presion� "f" si lo que vio era un hombre, "j" si era una mujer ', 100, scrHeight/2);
    Screen('Flip', wPtr);
    
    %Decrease step size while getting closer to the middle
    dif = femaleIndex - maleIndex;
    if (dif < 25 && dif >= 20)
        step = 3;
        else if (dif < 20 && dif >= 20)
            step = 2;
            else if (dif < 15)
                step = 1;
            end
        end
    end
    
    %fetch keystroke and process it
    [s keyCode ds] = KbStrokeWait();
    keyCode = find(keyCode);
    while (keyCode ~= leftMore && keyCode ~= rightMore)
        Screen('FillRect',wPtr,white);
        DrawFormattedText(wPtr, 'Por favor presione una tecla valida. \nf(hombre) o j(mujer)', 10, scrHeight/2);
        Screen('Flip', wPtr);
        [s keyCode ds] = KbStrokeWait();
        keyCode = find(keyCode);
    end
    
    %check if male was selected by the user
    if (keyCode==leftMore)
        male=1;
    else
        male=0; 
    end
    
    if( xor(male, maleTurn) == 1 )
        %in a male turn, female was answered or in female turn, male was
        %answered
        muZero = k;
    end
    maleTurn = xor(maleTurn,1);
end


DrawFormattedText(wPtr, 'Par�metros ajustados! Presione una tecla para comenzar', 100, scrHeight/2);
Screen('Flip', wPtr);
KbStrokeWait();
%%%%%%%%%%%% End Adaptive muZero testing %%%%%%%%%%%%%
imageIndex0 = muZero


vbl = Screen('Flip', wPtr);


for t=1:qtyTrials
    
        
    %start index from normal distribution
    %imageIndex0 = round(normrnd(qtyFaces/2,sigma));
    
    %start index fixed at midpoint
    %imageIndex = round(qtyFaces/2);
    
    %start index chosen randomly between 22 and 29
    %now 21 to 30
    %imageIndex0 = 9*binornd(1,0.5)+21; %imageIndex0 now will be given in
    %adaptive way.
    
    
    for i=1:sequenceSize
        
        %index of image selected from a uniform distribution
        %imageIndex = round(unifrnd(qtyFaces/2-sigma/2,qtyFaces/2+sigma/2));
        
        %index of image selected from a normal distribution
        imageIndex(i) = round(normrnd(imageIndex0,sigma));
        
        %from a random walk, same as previous +/- 1, with prob 0.5 each
        %side.
        %imageIndex = imageIndex + 2*binornd(1,0.5) - 1;
        
        while (imageIndex(i) < 1 || imageIndex(i) > qtyFaces)
            %if there's an invalid index, "reshuffle" until achieve a valid
            %value ("busy reshufle" might not be optimal)!!!.
            
            imageIndex(i) = round(normrnd(imageIndex0,sigma));    %for Normal
            %imageIndex = imageIndex + 2*binornd(1,0.5) - 1;  %for RW

        
        end

        Screen('DrawTexture', wPtr, gallery{imageIndex(i)}, [0 0 imgWidth imgHeight], [0 0 scrWidth scrHeight]); %resize to fill screen 
        vbl = Screen('Flip', wPtr, vbl + refresh * (qtyFrames - 0.4));
    end
    
    Screen('FillRect',wPtr,white);
    DrawFormattedText(wPtr, 'Por favor indique su eleccion: hombre (f +,d -) o mujer (j +,k -).', 100, scrHeight/2);
    Screen('Flip', wPtr);
    
    [s keyCode ds] = KbStrokeWait();
    keyCode = find(keyCode);
    while (keyCode ~= leftMore && keyCode ~= leftLess && keyCode ~= rightMore && keyCode ~= rightLess)
        Screen('FillRect',wPtr,white);
        DrawFormattedText(wPtr, 'Por favor presione una tecla valida. \nf(hombre+), d(hombre-), j(mujer+), k(mujer-)', 10, scrHeight/2);
        Screen('Flip', wPtr);
        [s keyCode ds] = KbStrokeWait();
        keyCode = find(keyCode);
    end
    
    
    if (keyCode==leftMore || keyCode ==leftLess)
        male=1;
    else
        male=0; 
    end
    
    if (keyCode==leftMore || keyCode ==rightMore)
        confidence=1;
    else
        confidence=0;
    end
    
    %Screen('FillRect',wPtr,white);
    %DrawFormattedText(wPtr, strcat('Ud apreto: ',KbName(keyCode)), 10, scrHeight/2);
    %Screen('Flip', wPtr);
    
    
    %write to file
    fwrite(fileID, t);
    fwrite(fileID,imageIndex0);
    fwrite(fileID, imageIndex);
    fwrite(fileID, male);
    fwrite(fileID, confidence);
    %read with
    %fread(filename, [sequenceSize+4 qtyTrials]);
    
    %ascii attempt.. how to put variable amount (sequenceSize) of %d's??
    %fprintf(fileID, '%d %d %d\n', i, imageIndex0, imageIndex);
    
    WaitSecs(1);
    
    %rest!
    if(mod(t,100)==0)
        DrawFormattedText(wPtr, 'Recreo! Pulse una tecla para continuar el test!', 10, scrHeight/2);
        Screen('Flip', wPtr); 
        KbStrokeWait();
    end
        
        
end

Screen('CloseAll');
ShowCursor;
fclose(fileID);

return;